﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using BLL;
using BLL.Managers;
using MessageBoxUtils;

namespace CorporateGymManagementSystem
{
    /// <summary>
    /// Interaction logic for ComposeNewMessageWindow.xaml
    /// </summary>
    public partial class ComposeNewMessageWindow : Window
    {
        private readonly ObservableCollection<GymWorker> workers = new ObservableCollection<GymWorker>(GymWorkerManager.Instance.GetWorkers());
        private readonly ObservableCollection<GymWorker> recipients = new ObservableCollection<GymWorker>();
        private readonly ObservableCollection<Trainee> trainees = new ObservableCollection<Trainee>(TraineeManager.Instance.GetTrainees());
        private readonly ObservableCollection<Trainee> traineesRecipients = new ObservableCollection<Trainee>();
        private string messageSubject;
        private string messageContent;
        private GymWorker loggedInWorker;
        private bool isMessageSent = false;
        private eComposeType composeType;

        public ComposeNewMessageWindow(GymWorker i_LoggedInWorker, eComposeType composeType)
        {
            InitializeComponent();
            this.composeType = composeType;
            loggedInWorker = i_LoggedInWorker;
            initalizeWindow();
            if (composeType == eComposeType.MessageBoardMessage || composeType == eComposeType.BroadcastMessage)
            {
                workersComboBox.Visibility = Visibility.Collapsed;
                addedRecipientsComboBox.Visibility = Visibility.Collapsed;
                addRecipientButton.Visibility = Visibility.Collapsed;
                removeRecipientButton.Visibility = Visibility.Collapsed;
                listOfWorkersLabel.Visibility = Visibility.Collapsed;
                arrangeDisplayLabel();
            }
        }


        public ComposeNewMessageWindow(GymWorker loggedInUser, GymWorker sender, string subject, string content, eComposeType composeType)
        {
            InitializeComponent();
            initalizeWindow();
            this.loggedInWorker = loggedInUser;
            
            subjectTextBox.Text = "RE: " + subject;
            for (int i = 0; i < workers.Count; i++)
            {
                if (workers[i].WorkerId == sender.WorkerId)
                {
                    recipients.Add(workers[i]);
                    workers.RemoveAt(i);
                    break;
                }
            }
            
            arrangeDisplayLabel();
            subjectTextBox.IsEnabled = false;
            contentTextBox.Text = content;
            this.composeType = composeType;
        }

        public ComposeNewMessageWindow(GymWorker loggedInUser, string subject, string content, eComposeType composeType)
        {
            InitializeComponent();
            initalizeWindow();
            this.loggedInWorker = loggedInUser;

            subjectTextBox.Text = "FW: " + subject;
            subjectTextBox.IsEnabled = false;
            contentTextBox.Text = content;
            this.composeType = composeType;
        }

        private void initalizeWindow()
        {
            if (workersComboBox.SelectedItem == null)
            {
                addRecipientButton.IsEnabled = false;
            }

            if (addedRecipientsComboBox.SelectedItem == null)
            {
                removeRecipientButton.IsEnabled = false;
            }

            if(contentTextBox.Text == string.Empty)
            {
                toolBarDiscardMessageButton.IsEnabled = false;
            }
            else
            {
                toolBarDiscardMessageButton.IsEnabled = true;
            }

            bindComboBoxes();
        }

        private void bindComboBoxes()
        {
            if (composeType.Equals(eComposeType.TraineeMessage))
            {
                workersComboBox.DataContext = trainees;
                addedRecipientsComboBox.DataContext = traineesRecipients;
            }
            else
            {
                workersComboBox.DataContext = workers;
                addedRecipientsComboBox.DataContext = recipients;
            }
        }

        private void addRecipientButton_Click(object sender, RoutedEventArgs e)
        {
            if(workersComboBox.SelectedItem != null/* && !recipients.Contains((GymWorker)workersComboBox.SelectedItem)*/)
            {
                if (composeType == eComposeType.TraineeMessage)
                {
                    traineesRecipients.Add(workersComboBox.SelectedItem as Trainee);
                    trainees.Remove(workersComboBox.SelectedItem as Trainee);
                }

                else
                {
                    recipients.Add((GymWorker)workersComboBox.SelectedItem);
                    workers.Remove((GymWorker)workersComboBox.SelectedItem);
                }
                arrangeDisplayLabel();

                workersComboBox.SelectedItem = null;
            }
        }

        private void removeRecipientButton_Click(object sender, RoutedEventArgs e)
        {
            if (addedRecipientsComboBox.SelectedItem != null/* && !workers.Contains((GymWorker)addedRecipientsComboBox.SelectedItem)*/)
            {
                if (composeType == eComposeType.RegularMessage)
                {
                    workers.Add((GymWorker)addedRecipientsComboBox.SelectedItem);
                    recipients.Remove((GymWorker)addedRecipientsComboBox.SelectedItem);
                }
                else if (composeType == eComposeType.TraineeMessage)
                {
                    trainees.Add(addedRecipientsComboBox.SelectedItem as Trainee);
                    traineesRecipients.Remove(addedRecipientsComboBox.SelectedItem as Trainee);
                }

                arrangeDisplayLabel();

                addedRecipientsComboBox.SelectedItem = null;
            }
        }

        private void arrangeDisplayLabel()
        {
            StringBuilder recipientsStringBuilder = new StringBuilder();

            if (composeType == eComposeType.MessageBoardMessage)
            {
                recipientsDisplayLabel.Content = "Messageboard Message";
            }
            else if (composeType == eComposeType.BroadcastMessage)
            {
                recipientsDisplayLabel.Content = "All Trainees";
            }
            else
            {
                if (recipients.Count == 0 && traineesRecipients.Count == 0)
                {
                    recipientsDisplayLabel.Content = "None";
                }
                else
                {
                    if (composeType == eComposeType.RegularMessage)
                    {
                        foreach (GymWorker recipient in recipients)
                        {
                            recipientsStringBuilder.Append(recipient.FullName);
                            recipientsStringBuilder.Append("; ");
                        }
                    }
                    else if (composeType == eComposeType.TraineeMessage)
                    {
                        foreach (Trainee trainee in traineesRecipients)
                        {
                            recipientsStringBuilder.Append(trainee.FullName);
                            recipientsStringBuilder.Append("; ");
                        }
                    }

                    recipientsDisplayLabel.Content = recipientsStringBuilder.ToString();
                }

                toggleDiscardButtonEnabledState();
            }
        }

        private void workersComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(workersComboBox.SelectedItem != null)
            {
                addRecipientButton.IsEnabled = true;
            }
            else
            {
                addRecipientButton.IsEnabled = false;
            }
        }

        private void addedRecipientsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (addedRecipientsComboBox.SelectedItem != null)
            {
                removeRecipientButton.IsEnabled = true;
            }
            else
            {
                removeRecipientButton.IsEnabled = false;
            }
        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!isMessageSent)
            {
                e.Cancel = tryClose();
            }
        }

        private bool tryClose()
        {
            MessageBoxResult isDiscard = WPFMessageBox.Show("Your message will be lost. Are you sure?", "Discard", MessageBoxButton.YesNo, MessageBoxImage.Question);
            bool isClose = true;

            switch (isDiscard)
            {
                case MessageBoxResult.Yes:
                    isClose = false;
                    break;
                case MessageBoxResult.No:
                    isClose = true;
                    break;
            }

            return isClose;
        }

        private void contentsTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            toggleDiscardButtonEnabledState();
        }

        private void sendMessageToRecipients()
        {
            if (composeType == eComposeType.MessageBoardMessage)
            {
                try
                {
                    MessagesManager.Instance.PostMessageToMessageBoard(loggedInWorker.WorkerId, messageSubject, messageContent);
                    isMessageSent = true;
                    this.Close();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.StackTrace.ToString());
                }
            }
            else if (composeType == eComposeType.BroadcastMessage)
            {
                try
                {
                    MessagesManager.Instance.BroadcastMessage(messageSubject, messageContent);
                    isMessageSent = true;
                    this.Close();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.StackTrace.ToString());
                }
            }
            else if(composeType == eComposeType.RegularMessage)
            {
                List<int> recipientsWorkerIdList = new List<int>();
                foreach (GymWorker Recipient in recipients)
                {
                    recipientsWorkerIdList.Add(Recipient.WorkerId);
                }
                try
                {
                    MessagesManager.Instance.SendMessage(loggedInWorker.WorkerId, messageSubject, messageContent, recipientsWorkerIdList);
                    isMessageSent = true;
                    this.Close();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.StackTrace.ToString());
                }
            }
            else if (eComposeType.TraineeMessage == composeType)
            {
                try
                {
                    List<string> emails =  new List<string>();
                    foreach (var trainee in traineesRecipients)
	                {
	            	    emails.Add((trainee as Trainee).Email);
	                }

                    MessagesManager.Instance.sendEmailToRecipients(emails, messageSubject, messageContent);
                    isMessageSent = true;
                    this.Close();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }

        private void closeComposeWindowButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void subjectTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            toggleDiscardButtonEnabledState();
        }

        private void toggleDiscardButtonEnabledState()
        {
            if (contentTextBox.Text == string.Empty && subjectTextBox.Text == string.Empty && recipientsDisplayLabel.Content.Equals("None"))
            {
                toolBarDiscardMessageButton.IsEnabled = false;
            }
            else
            {
                toolBarDiscardMessageButton.IsEnabled = true;
            }
        }

        private void ButtonBar_Loaded(object sender, RoutedEventArgs e)
        {
            ToolBar toolBar = sender as ToolBar;
            var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;
            if (overflowGrid != null)
            {
                overflowGrid.Visibility = Visibility.Collapsed;
            }
        }

        private void toolBarSendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            if (subjectTextBox.Text == string.Empty || contentTextBox.Text == string.Empty || (recipients.Count == 0 && composeType == eComposeType.RegularMessage))
            {
                if (subjectTextBox.Text == string.Empty && contentTextBox.Text == string.Empty && recipients.Count == 0)
                {
                    WPFMessageBox.Show("Recipient and subject and message content missing!", "Invalid message format", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                else if (subjectTextBox.Text == string.Empty)
                {
                    WPFMessageBox.Show("Subject missing!", "Invalid message format", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                else if (contentTextBox.Text == string.Empty)
                {
                    WPFMessageBox.Show("Message content missing!", "Invalid message format", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                else
                {
                    WPFMessageBox.Show("Recipient missing!", "Invalid message format", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
            }
            else
            {
                messageSubject = subjectTextBox.Text;
                messageContent = contentTextBox.Text;

                sendMessageToRecipients();
            }
        }

        private void toolBarDiscardMessageButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult isDiscard = WPFMessageBox.Show("Your message will be lost. Are you sure?", "Discard", MessageBoxButton.YesNo, MessageBoxImage.Question);

            switch (isDiscard)
            {
                case MessageBoxResult.Yes:
                    subjectTextBox.Text = string.Empty;
                    contentTextBox.Text = string.Empty;
                    foreach (GymWorker recipient in recipients)
                    {
                        workers.Add(recipient);
                    }

                    ObservableCollection<GymWorker> tempList = new ObservableCollection<GymWorker>(recipients);

                    foreach (GymWorker recipient in tempList)
                    {
                        recipients.Remove(recipient);
                    }

                    workersComboBox.SelectedItem = null;
                    addedRecipientsComboBox.SelectedItem = null;
                    arrangeDisplayLabel();
                    break;
                case MessageBoxResult.No:
                    break;
            }
        }

        
    }
}
